from flask import Blueprint
from flask import Flask, flash, request, redirect, url_for, current_app
from flask.json import jsonify
from flask_login.utils import login_required
from flask_login import current_user
from werkzeug.utils import secure_filename
from datetime import datetime
import os
from paddy_doctor.model.database import mongo
from paddy_doctor.models.resnet import ResnetClassifier
from PIL import Image
import uuid
import json

mod = Blueprint('classifier', __name__)
resnet = ResnetClassifier()


# 接收二进制图片，返回分类结果
@mod.route('/classify/<modelId>', methods=['POST'])
@login_required
def classify(modelId):
    if 'file' not in request.files:
        return {'type': 'none', 'text': '没有文件'}
    # file的类型是werkzeug.datastructures.FileStorage
    file = request.files['file']
    if file.filename == '':
        return {'type': 'none', 'text': '未选中文件'}
    if file:
        # 生成文件名
        rawname = secure_filename(file.filename)
        ext = os.path.splitext(rawname)[-1]
        fileid = str(uuid.uuid4())
        filename = fileid + ext
        # 保存文件到磁盘
        path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
        # 修改了图片存储路径
        path = os.path.join('paddy_doctor', path)
        file.save(path)

        img = Image.open(path)
        # tag, conf = imagenet.classify(img)
        # TODO 校验模型名称的合法性
        tag, conf = resnet.classify(modelId, img)
        # TODO 实际上不明地点与匿名用户识别的不应当记录
        if current_user.is_authenticated:
            mongo.db.record.insert_one({
                'userid': current_user.id, 'modelid': modelId,
                'result': tag, 'confidence': conf,
                'time':  datetime.utcnow(), 'location': current_user.location,
                'fileid': fileid, 'fileext': ext})
        return {'type': tag,'confidence': conf, 'text': f'置信度为{conf}', 'fileid': fileid}
    return {'type': 'none', 'text': '文件为空'}

# 测试用
@mod.route('/test', methods=['GET'])
@login_required
def test():
    # TODO 删除此API
    if hasattr(current_user, 'id'):
        return {'text': current_user.is_authenticated, 'id': current_user.id}
    return {'text': current_user.is_authenticated}

# 接收反馈
@mod.route('/feedback', methods=['POST'])
@login_required
def feedback():
    info = json.loads(request.data)
    fileid = info.get('fileid')
    text = info.get('feedback')
    result = mongo.db.record.find_one({'userid': current_user.id, 'fileid': fileid})
    if result != None:
        mongo.db.feedback.insert_one({'userid': current_user.id, 'fileid': fileid, 'feedback': text})
    return jsonify({'status': 'success'})

# 获取历史反馈
@mod.route('/feedback', methods=['GET'])
@login_required
def getFeedback():
    result = mongo.db.feedback.find({'userid': current_user.id}, {'_id': 0}).sort([('_id', -1)])
    return jsonify({'status': 'success', 'result': list(result)})

@mod.route('/knowledge', methods=['GET'])
def getKnowledge():
    with open('resource/introduction.json', mode='r', encoding='utf8') as f:
        data = json.load(f)
        return jsonify(data)

